package com.sywb.chuangyebao.view;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.Layout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.ChatSession;
import com.sywb.chuangyebao.bean.NewsOwner;
import com.sywb.chuangyebao.bean.UserIndex;
import com.sywb.chuangyebao.contract.UserIndexContract;
import com.sywb.chuangyebao.library.view.RatioImageView;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.Utils;

import org.bining.footstone.db.DbManager;
import org.bining.footstone.log.Logger;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.ToastUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 用户主页
 */
public class UserIndexActivity extends ActionbarActivity<UserIndexContract.Presenter> implements UserIndexContract.View {

    @BindView(R.id.cl_index)
    CoordinatorLayout clIndex;

    @BindView(R.id.abl_head)
    AppBarLayout ablHead;

    @BindView(R.id.ctl_head)
    CollapsingToolbarLayout ctlHead;

    @BindView(R.id.iv_index)
    RatioImageView ivIndex;

    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.iv_label)
    ImageView ivLabel;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_user_type)
    TextView tvUserType;
    @BindView(R.id.tv_user_info)
    TextView tvUserInfo;

    @BindView(R.id.tv_send_message)
    TextView tvSendMessage;
    @BindView(R.id.tv_add_focus)
    TextView tvAddFocus;

    @BindView(R.id.ll_sign_one)
    LinearLayout llSignOne;
    @BindView(R.id.tv_sign_one)
    TextView tvSignOne;
    @BindView(R.id.tv_spread)
    TextView tvSpread;

    @BindView(R.id.ll_sign_two)
    LinearLayout llSignTwo;
    @BindView(R.id.tv_sign_two)
    TextView tvSignTwo;
    @BindView(R.id.tv_fold)
    TextView tvFold;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rl_toolbar)
    RelativeLayout rlToolbar;
    @BindView(R.id.tv_toolbar_back)
    ImageView tvToolbarBack;
    @BindView(R.id.tv_toolbar_title)
    TextView tvToolbarTitle;
    @BindView(R.id.ll_add_focus_head)
    RelativeLayout llAddFocusHead;
    @BindView(R.id.tv_add_focus_head)
    TextView tvAddFocusHead;

    @BindView(R.id.page_title1)
    TextView pageTitle1;
    @BindView(R.id.page_title2)
    TextView pageTitle2;
    @BindView(R.id.page_title3)
    TextView pageTitle3;
    @BindView(R.id.page_title4)
    TextView pageTitle4;
    @BindView(R.id.page_title5)
    TextView pageTitle5;
    @BindView(R.id.page_title6)
    TextView pageTitle6;

    @BindView(R.id.tv_consult)
    TextView tvConsult;

    @BindView(R.id.vp_index)
    ViewPager vpIndex;

    private CollapsingToolbarLayoutState state = CollapsingToolbarLayoutState.EXPANDED;

    /**
     * CollapsingToolbarLayout展开、折叠、中间，这三种状态
     */
    private enum CollapsingToolbarLayoutState {
        EXPANDED,// 展开
        COLLAPSED,// 折叠
        INTERNEDIATE// 中间状态
    }

    private int uid;
    private int whichOne;
    private String name;

    int ellipsisCount;
    private boolean isFollowed;
    private UserIndex userIndex;
    private String userSign;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_user_index;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("p0", uid);
        outState.putInt("p1", whichOne);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void initView(Bundle bundle) {
        super.initView(bundle);
        if (bundle == null) {
            uid = getIntent().getIntExtra("p0", 0);
            whichOne = getIntent().getIntExtra("p1", 0);
        } else {
            uid = bundle.getInt("p0");
            whichOne = bundle.getInt("p1");
        }

        ablHead.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                Logger.e("verticalOffset:" + verticalOffset + " getTotalScrollRange:" + appBarLayout.getTotalScrollRange());

                if (verticalOffset == 0) {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        // 设置展开状态下的界面状态
                        tvToolbarBack.setImageResource(R.drawable.ic_back_white);
                    }
                    rlToolbar.getBackground().setAlpha(0);
                    state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                        // 设置折叠状态下的界面状态
                        tvToolbarBack.setImageResource(R.drawable.ic_back_black);

                        tvToolbarTitle.setVisibility(View.VISIBLE);
                        llAddFocusHead.setVisibility(View.VISIBLE);

                        toolbar.setTitle("");
                        ctlHead.setTitle("");

                    }
                    rlToolbar.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                } else {
                    float percentage = (float) Math.abs(verticalOffset) / (float) appBarLayout.getTotalScrollRange();
                    if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                        if (percentage <= 0.7) {
                            tvToolbarBack.setImageResource(R.drawable.ic_back_white);
                            tvToolbarTitle.setVisibility(View.GONE);
                            llAddFocusHead.setVisibility(View.GONE);
                        } else {
                            tvToolbarBack.setImageResource(R.drawable.ic_back_black);
                            tvToolbarTitle.setVisibility(View.VISIBLE);
                            llAddFocusHead.setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (percentage >= 0.7) {
                            tvToolbarBack.setImageResource(R.drawable.ic_back_black);
                            tvToolbarTitle.setVisibility(View.VISIBLE);
                            llAddFocusHead.setVisibility(View.VISIBLE);
                        } else {
                            tvToolbarBack.setImageResource(R.drawable.ic_back_white);
                            tvToolbarTitle.setVisibility(View.GONE);
                            llAddFocusHead.setVisibility(View.GONE);
                        }
                    }

                    float alpha = 255 * percentage;
                    if (alpha > 16) {
                        String alphaString = Integer.toHexString((int) alpha);
                        Logger.e("percentage:" + percentage + " alpha:" + alpha + " alphaString:" + alphaString);
                        rlToolbar.setBackgroundColor(Color.parseColor("#" + alphaString + "FFFFFF"));
                    }
                    // state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                }
            }
        });

        setSupportActionBar(toolbar);
        toolbar.setTitle("");
        ctlHead.setTitle("");
        //使用CollapsingToolbarLayout必须把title设置到CollapsingToolbarLayout上，设置到Toolbar上则不会显示
        //通过CollapsingToolbarLayout修改字体颜色
        ctlHead.setExpandedTitleColor(Color.TRANSPARENT);//设置还没收缩时状态下字体颜色
        ctlHead.setExpandedTitleGravity(Gravity.CENTER);
        ctlHead.setCollapsedTitleTextColor(ContextCompat.getColor(mActivity, R.color.colorDark));//设置收缩后Toolbar上字体的颜色
        ctlHead.setCollapsedTitleGravity(Gravity.CENTER);
        ctlHead.setStatusBarScrimColor(Color.TRANSPARENT);

        rlToolbar.setBackgroundColor(Color.parseColor("#00FFFFFF"));

        String myOpenId = SharedUtils.getString(Constants.USEROPENID);

        if (myOpenId.equals(String.valueOf(uid))) {
            tvSendMessage.setVisibility(View.INVISIBLE);
            tvAddFocus.setVisibility(View.INVISIBLE);
            tvAddFocusHead.setVisibility(View.INVISIBLE);
        } else {
            tvSendMessage.setVisibility(View.VISIBLE);
            tvAddFocus.setVisibility(View.VISIBLE);
            tvAddFocusHead.setVisibility(View.VISIBLE);
        }

        clIndex.setVisibility(View.INVISIBLE);
        getUserData();
    }

    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
    }

    private void getUserData() {
        HttpUtils.getUser(uid, new HttpCallback<UserIndex>() {

            @Override
            public void onStart() {
                super.onStart();
                showProgress();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                hideProgress();
            }

            @Override
            public void onSuccess(UserIndex userInfo) {
                if (userInfo == null) {
                    return;
                }
                userIndex = userInfo;

                tvToolbarTitle.setText(userInfo.getShowName());
                userSign = userInfo.brief_intro;
                initSignView();

                GlideUtils.getCircleImageToUrl(mActivity, userInfo.getShowAvatar(), ivAvatar);
                tvUsername.setText(userInfo.getShowName());

                ivLabel.setVisibility(View.VISIBLE);
                tvUserType.setVisibility(View.VISIBLE);
                int defaultBg = 0;

                int userRole = userInfo.getUserRole();
                switch (userRole) {
                    case Constants.USER_TYPE_NORMAL:
                        ivLabel.setVisibility(View.GONE);
                        tvUserType.setVisibility(View.GONE);
                        defaultBg = R.drawable.user_bg;
                        break;
                    case Constants.USER_TYPE_V:
                        ivLabel.setImageResource(R.drawable.official_icon);
                        tvUserType.setText("官方号");
                        defaultBg = R.drawable.user_bg;
                        break;
                    case Constants.USER_TYPE_PROJECT:
                        ivLabel.setImageResource(R.drawable.icon_project);
                        tvUserType.setText("项目号");
                        defaultBg = R.drawable.project_number_bg;
                        break;
                    case Constants.USER_TYPE_SERVICE:
                        ivLabel.setImageResource(R.drawable.icon_service);
                        tvUserType.setText("服务商");
                        defaultBg = R.drawable.provider_bg;
                        break;
                    case Constants.USER_TYPE_TUTOR:
                        ivLabel.setImageResource(R.drawable.icon_teacher);
                        tvUserType.setText("导师");
                        defaultBg = R.drawable.tutor_bg;
                        break;
                }

                if (userRole == Constants.USER_TYPE_PROJECT) {
                    setConsultState(true);
                } else {
                    setConsultState(false);
                }

                setRolePageData(userRole);

                if (!TextUtils.isEmpty(userInfo.bg_img)) {
                    GlideUtils.getNormalIamgeToUrl(mActivity, userInfo.bg_img, ivIndex, defaultBg);
                } else {
                    ivIndex.setImageResource(defaultBg);
                }

                isFollowed = userInfo.is_follow;
                setFollowView(userInfo.is_follow);
                tvUserInfo.setText(userInfo.follow_num + " 关注   |   " + userInfo.fans_num + "  粉丝");

                clIndex.setVisibility(View.VISIBLE);
            }
        });
    }

    private void initSignView() {
        tvSignOne.setText(userSign);
        //异步获取高度
        tvSignOne.post(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(200);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (tvSignOne == null) {
                                return;
                            }
                            Layout layout = tvSignOne.getLayout();
//                            int lineCount = layout.getLineCount();
//                            Logger.e("lineCount:" + lineCount);
                            if (layout == null) {
                                return;
                            }
                            ellipsisCount = layout.getEllipsisCount(0);
                            Logger.e("ellipsisCount:" + ellipsisCount);
                            if (ellipsisCount > 0) {
                                //超过一行了 展示收起状态
//                                tvSignOne.setSingleLine();
                                tvSignOne.setEllipsize(TextUtils.TruncateAt.END);
                                tvSpread.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setRolePageData(int userRole) {

        pageTitle1.setVisibility(View.VISIBLE);
        pageTitle2.setVisibility(View.GONE);
        pageTitle3.setVisibility(View.GONE);
        pageTitle4.setVisibility(View.GONE);
        pageTitle5.setVisibility(View.GONE);
        pageTitle6.setVisibility(View.GONE);

        switch (userRole) {
            case Constants.USER_TYPE_NORMAL:
                pageTitle2.setVisibility(View.VISIBLE);
                pageTitle3.setVisibility(View.VISIBLE);
                break;
            case Constants.USER_TYPE_PROJECT:
                pageTitle2.setVisibility(View.VISIBLE);
                pageTitle3.setVisibility(View.VISIBLE);

                if (userIndex.topic_id > 0) {
                    pageTitle4.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(userIndex.web_url)) {
                    pageTitle5.setVisibility(View.VISIBLE);
                }

                break;
            case Constants.USER_TYPE_SERVICE:
                pageTitle6.setVisibility(View.VISIBLE);
                break;
        }

        setSelectPageItem(0);
        mPresenter.initPageData(userRole);
        mPresenter.setCurrentPage(whichOne);
    }

    @OnClick({R.id.tv_toolbar_back, R.id.tv_spread, R.id.tv_fold, R.id.page_title1, R.id.page_title2, R.id.page_title3, R.id.page_title4, R.id.page_title5, R.id.page_title6,
            R.id.tv_add_focus, R.id.tv_add_focus_head, R.id.tv_send_message, R.id.tv_consult})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_toolbar_back:
                exit();
                break;
            case R.id.tv_spread:
                //获取第一行显示的总字数
                tvSpread.setVisibility(View.GONE);
                tvSignOne.setEllipsize(null);
//                tvSignOne.setText(userSign.substring(0, ellipsisCount - 1));
                String showSecondLine = userSign.substring(userSign.length() - ellipsisCount + 1);
                tvSignTwo.setText(showSecondLine);
                llSignTwo.setVisibility(View.VISIBLE);
                tvFold.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_fold:
                llSignTwo.setVisibility(View.INVISIBLE);
                tvSpread.setVisibility(View.VISIBLE);
                tvSignOne.setEllipsize(TextUtils.TruncateAt.END);
                break;
            case R.id.page_title1:
                setSelectPageItem(0);
                mPresenter.setCurrentPage(0);
                break;
            case R.id.page_title2:
                setSelectPageItem(1);
                mPresenter.setCurrentPage(1);
                break;
            case R.id.page_title3:
                setSelectPageItem(2);
                mPresenter.setCurrentPage(2);
                break;
            case R.id.page_title4:
                //话题
                advance(TopicActivity.class, userIndex.topic_id);
                break;
            case R.id.page_title5:
                //官网
                advance(WebActivity.class, pageTitle5.getText().toString(), userIndex.web_url);
                break;
            case R.id.page_title6:
                //服务
                advance(WebActivity.class, pageTitle6.getText().toString(), userIndex.service_url);
                break;
            case R.id.tv_add_focus:
            case R.id.tv_add_focus_head:
                //判断是否登录
                if (!Utils.checkIsLogin()) {
                    return;
                }
                HttpUtils.follow(uid, Constants.TOPIC_TYPE_USER, !isFollowed, new HttpCallback<Object>() {

                    @Override
                    public void onStart() {
                        super.onStart();
                        showProgress();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        hideProgress();
                    }

                    @Override
                    public void onSuccess(Object s) {
                        ToastUtils.show(mContext, isFollowed ? "取消关注" : "关注成功");
                        isFollowed = !isFollowed;
                        setFollowView(isFollowed);
                    }

                    @Override
                    public void onError(String strMsg) {
                        super.onError(strMsg);
                        showMessage(strMsg);
                    }
                });
                break;
            case R.id.tv_send_message:
                if (!Utils.checkIsLogin()) {
                    return;
                }
                HttpUtils.isShield(String.valueOf(uid), new HttpCallback<Boolean>() {

                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        Logger.e("onSuccess:" + aBoolean);
                        if (aBoolean) {
                            ToastUtils.show(mActivity, "抱歉，您已拉黑该用户，暂不能发私信");
                        } else {
                            try {
                                ChatSession chatSession = DbManager.getInstance().queryById(uid, ChatSession.class);
                                if (chatSession == null) {
                                    chatSession = new ChatSession();
                                    chatSession.session_uid = uid;
                                    chatSession.my_uid = Integer.valueOf(SharedUtils.getString(Constants.USEROPENID));
                                    chatSession.msg = "";
                                    chatSession.create_time = System.currentTimeMillis() / 1000;
                                    chatSession.status = 1;

                                    NewsOwner newsOwner = new NewsOwner();
                                    newsOwner.uid = uid;
                                    newsOwner.name = userIndex.username;
                                    newsOwner.nickname = userIndex.nickname;
                                    newsOwner.avatar_s = userIndex.avatar_s;
                                    newsOwner.avatar_l = userIndex.avatar_l;
                                    newsOwner.avatar_hd = userIndex.avatar_hd;
                                    newsOwner.brief_intro = userIndex.brief_intro;
                                    newsOwner.user_role = userIndex.user_role;

                                    chatSession.owner = JSON.toJSONString(newsOwner);

                                    DbManager.getInstance().save(chatSession);
                                }
                                advance(UserChatActivity.class, uid);
                            } catch (Exception e) {
                                showMessage("用户信息错误,无法发送私信");
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(String strMsg) {
                        super.onError(strMsg);
                        showMessage(strMsg);
                    }
                });
                break;
            case R.id.tv_consult:
                HttpUtils.getCode(userIndex.project_id, 0, new HttpCallback<String>() {

                    @Override
                    public void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onSuccess(String s) {
                        if (TextUtils.isEmpty(s)) {
                            return;
                        }
                        advance(WebActivity.class, "畅谈通", s, Constants.COOKIE_XMH);
                    }

                    @Override
                    public void onError(String strMsg) {
                        super.onError(strMsg);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                });
                break;
        }
    }

    @Override
    public FragmentManager getUserFragmentManager() {
        return getSupportFragmentManager();
    }

    @Override
    public ViewPager getViewpager() {
        return vpIndex;
    }

    @Override
    public int getUid() {
        return uid;
    }

    @Override
    public void setSelectPageItem(int postion) {
        pageTitle1.setTextColor(ContextCompat.getColor(mContext, R.color.colorDark));
        pageTitle2.setTextColor(ContextCompat.getColor(mContext, R.color.colorDark));
        pageTitle3.setTextColor(ContextCompat.getColor(mContext, R.color.colorDark));
        pageTitle4.setTextColor(ContextCompat.getColor(mContext, R.color.colorDark));
        pageTitle5.setTextColor(ContextCompat.getColor(mContext, R.color.colorDark));
        pageTitle6.setTextColor(ContextCompat.getColor(mContext, R.color.colorDark));

        switch (postion) {
            case 0:
                pageTitle1.setTextColor(ContextCompat.getColor(mContext, R.color.colorTheme));
                break;
            case 1:
                pageTitle2.setTextColor(ContextCompat.getColor(mContext, R.color.colorTheme));
                break;
            case 2:
                pageTitle3.setTextColor(ContextCompat.getColor(mContext, R.color.colorTheme));
                break;
            case 3:
                pageTitle4.setTextColor(ContextCompat.getColor(mContext, R.color.colorTheme));
                break;
            case 4:
                pageTitle5.setTextColor(ContextCompat.getColor(mContext, R.color.colorTheme));
                break;
            case 5:
                pageTitle6.setTextColor(ContextCompat.getColor(mContext, R.color.colorTheme));
                break;
        }
    }

    public void setFollowView(boolean isConcern) {
        tvAddFocus.setText(isConcern ? R.string.btn_attentioned : R.string.add_focus);
        tvAddFocusHead.setText(isConcern ? R.string.btn_attentioned : R.string.add_focus);
        if (isConcern) {
            tvAddFocus.setTextColor(ContextCompat.getColor(mActivity, R.color.colorGray));
            tvAddFocus.setBackgroundResource(R.drawable.round3_pie_gray_light);
            tvAddFocusHead.setBackgroundResource(R.drawable.round3_pie_gray_light);
        } else {
            tvAddFocus.setTextColor(ContextCompat.getColor(mActivity, R.color.colorTheme));
            tvAddFocus.setBackgroundColor(Color.WHITE);
            tvAddFocusHead.setBackgroundResource(R.drawable.round_pie_msg_unread);
        }

        Utils.setFolllowView(this, isConcern, tvAddFocusHead);
    }

    public void setConsultState(boolean isConsult) {
        tvConsult.setVisibility(isConsult ? View.VISIBLE : View.GONE);
    }
}
